Converting between vector types
Problem
You want to convert between Numeric vectors, Character vectors, and Factors.
Solution
Suppose you start with this Numeric vector n
:
n <- 10:14 # 10 11 12 13 14
To convert the Numeric vector to the other two (we_ll also save these results in c
and f
):
# Numeric to Character c <- as.character(n) # "10" "11" "12" "13" "14" # Numeric to Factor f <- factor(n) # 10 11 12 13 14 # Levels: 10 11 12 13 14
To convert the Character vector to the other two:
# Character to Numeric as.numeric(c) # 10 11 12 13 14 # Character to Factor factor(c) # 10 11 12 13 14 # Levels: 10 11 12 13 14
Converting a Factor to a Character vector is straightforward:
# Factor to Character as.character(f) # "10" "11" "12" "13" "14"
However, converting a Factor to a Numeric vector is a little trickier. If you just convert it with as.numeric
, it will give you the numeric coding of the factor, which probably isn't what you want.
as.numeric(f) # 1 2 3 4 5 # Another way to get the numeric coding, if that's what you want: unclass(f) # 1 2 3 4 5 # attr(,"levels") # "10" "11" "12" "13" "14"
The way to get the get the proper values is to first convert it to a Character vector, then a Numeric vector.
# Factor to Numeric as.numeric(as.character(f)) # 10 11 12 13 14